package com.xjgc.ws.mes.dao;

import com.xjgc.common.config.DbConn;
import com.xjgc.ws.util.CheckData;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 * 实现单表的XML数据解析并组装成SQL语句执行
 */
@Component
public class ZxjMesWerks {
    @Autowired
    DbConn db;

    @Autowired
    CheckData cData;
    /**
     * 解析报文xml
     * 返回执行结果：操作结果记录
     * @param xmlData
     * @return
     * @throws SQLException
     */
    public String werks(String xmlData) throws SQLException, ParseException {
        String rs = null;
        PreparedStatement delPst = null;
        PreparedStatement inPst = null;

        //定义执行SQL脚本
        String delSql = "delete from zxj_mes_werks where \"WERKS\"=?"; //删除SQL
        String inSql = "insert into zxj_mes_werks values(?,?,?,?,?,?)";  //22插入SQL

        //创建数据库连接
        delPst = db.getConnetion().prepareStatement(delSql);
        inPst = db.getConnetion().prepareStatement(inSql);
        int count=0;
        //解析xml文件
        Document doc = null;

        try {
            doc = DocumentHelper.parseText(xmlData);
            Element root = doc.getRootElement();
            Iterator<?> it = root.elementIterator();

            while(it.hasNext()) {
                Element element = (Element) it.next();

                delPst.setString(1, element.elementText("WERKS"));
                inPst.setString(1, element.elementText("WERKS"));
                inPst.setString(2, element.elementText("NAME1"));
                inPst.setString(3, element.elementText("PRCTR"));

                String datum = element.elementText("DATUM");
                Date yyyyMMdd = new SimpleDateFormat("yyyyMMdd").parse(datum);
                inPst.setDate(4,new java.sql.Date(yyyyMMdd.getTime()));

                String uzeit = element.elementText("UZEIT");
                java.util.Date hHmmss = new SimpleDateFormat("HHmmss").parse(uzeit);
                inPst.setTime(5,new Time(hHmmss.getTime()));

                inPst.setString(6, element.elementText("MESSAGE"));

                //删除更新数据
                delPst.executeUpdate();

                //插入更新数据
                int row = inPst.executeUpdate();
                if(row>0) {
                    count++;
                }
            }
            if (count>0) {
                rs = "0";//执行成功
            }
        } catch (DocumentException e1) {
            rs=e1.toString();//执行失败
            e1.printStackTrace();
        }
        //关闭连接
        delPst.close();
        inPst.close();
        db.closeCn();
        return rs;
    }


}
